package com.qf.spring.anno.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author nk
 * @date 2022/4/28 15:03
 * 作用:替换之前的beans.xml配置文件
 */
@Configuration //标识当前类是一个配置类
@ComponentScan("com.qf.spring.anno")
public class SpringConfig {
    //1、DataSource
    @Bean
    public static DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db2202?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //2、sqlSessionFactory
    @Bean
    public static SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //注入数据源
        factoryBean.setDataSource(dataSource());
        //获取mapper.xml资源文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
        //注入资源文件
        factoryBean.setMapperLocations(resources);
        //配置实体类的别名
        factoryBean.setTypeAliasesPackage("com.qf.spring.anno.entity");
        return factoryBean;
    }


    //3、MapperScannerConfigure
    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.qf.spring.anno.dao");
        return configurer;
    }

    //txManager
}
